package br.com.winesys.geta.editor;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;

public abstract class TabbedObjectEditor<Model> implements Editor<Model> {

	private JTabbedPane tabbedPane;
	private Model object;
	private Map<String, Editor<Model>> objectEditors = new LinkedHashMap<String, Editor<Model>>();

	public TabbedObjectEditor() {
		super();
		createObjectEditors();
		this.tabbedPane = new JTabbedPane();
		this.layoutObjectEditors();
	}

	protected abstract void createObjectEditors();

	protected void addObjectEditor(String text, Editor<Model> editor) {
		this.objectEditors.put(text, editor);
	}

	public Set<String> getObjectEditors() {
		return this.objectEditors.keySet();
	}

	public Editor<Model> getObjectEditor(String text) {
		return this.objectEditors.get(text);
	}

	@Override
	public JComponent getComponent() {
		return this.tabbedPane;
	}

	private void layoutObjectEditors() {
		for (String str : this.objectEditors.keySet()) {
			this.tabbedPane.add(str, this.objectEditors.get(str).getComponent());
		}
	}

	@Override
	public Model getObject() {
		for (Editor<Model> editor : this.objectEditors.values()) {
			editor.getObject();
		}
		return this.object;
	}

	@Override
	public Map<String, Object> getProperties() {
		Map<String, Object> map = new TreeMap<String, Object>();
		for (Editor<Model> editor : this.objectEditors.values()) {
			map.putAll(editor.getProperties());
		}
		return map;
	}

	@Override
	public void setObject(Model object) {
		this.object = object;
		for (Editor<Model> editor : this.objectEditors.values()) {
			editor.setObject(object);
		}
	}

	@Override
	public void setProperties(Map<String, Object> properties) {
		for (Editor<Model> editor : this.objectEditors.values()) {
			editor.setProperties(properties);
		}
	}
	
	@Override
	public void cleanValidation(){
		for (Editor<Model> editor : this.objectEditors.values()) {
			editor.cleanValidation();
		}
	}

	@Override
	public boolean validate() {
		boolean result = true;
		for (Editor<Model> editor : this.objectEditors.values()) {
			result &= editor.validate();
		}
		return result;
	}

	@Override
	public void setEnabled(boolean enabled) {
		for (Editor<Model> editor : this.objectEditors.values()) {
			editor.setEnabled(enabled);
		}
	}
}
